import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../../../common/api/index.dart';
import '../../../common/models/index.dart';

/// 活动管理页面控制器
class ActivityManageController extends GetxController {
  // ==================== 页面数据 ====================
  final activityId = 0.obs;
  final activityTitle = ''.obs;
  final participants = <ActivityParticipantData>[].obs;
  final isLoadingParticipants = false.obs;
  final isEmpty = false.obs;
  
  @override
  void onInit() {
    super.onInit();
    _initParameters();
  }
  
  /// 初始化参数
  void _initParameters() {
    try {
      final args = Get.arguments as Map<String, dynamic>?;
      
      if (args != null) {
        final id = args['activityId'] as int? ?? 0;
        final title = args['title'] as String? ?? '活动管理';
        
        activityId.value = id;
        activityTitle.value = title;
        
        debugPrint('👥 活动管理页面 - ID: $id, 标题: $title');
        
        // 加载参与者
        loadParticipants();
      }
    } catch (e) {
      debugPrint('❌ 参数初始化失败: $e');
    }
  }
  
  /// 加载活动参与者
  Future<void> loadParticipants() async {
    if (activityId.value == 0) {
      debugPrint('❌ 活动ID为空');
      return;
    }
    
    isLoadingParticipants.value = true;
    
    try {
      debugPrint('🔄 加载活动参与者');
      debugPrint('   活动ID: ${activityId.value}');
      
      final response = await ActivityApi.getActivityParticipants(
        activityId: activityId.value,
      );
      
      if (response.isSuccess && response.data != null) {
        participants.value = response.data!.participants;
        isEmpty.value = participants.isEmpty;
        
        debugPrint('✅ 参与者加载成功');
        debugPrint('   参与者数量: ${participants.length}');
      } else {
        debugPrint('❌ 参与者加载失败: ${response.message}');
        isEmpty.value = true;
      }
    } catch (e) {
      debugPrint('❌ 加载参与者异常: $e');
      isEmpty.value = true;
    } finally {
      isLoadingParticipants.value = false;
    }
  }
  
  /// 删除参与者
  Future<void> removeParticipant(int userId, String username) async {
    try {
      debugPrint('🗑️ 删除参与者');
      debugPrint('   用户ID: $userId');
      debugPrint('   用户名: $username');
      
      final response = await ActivityApi.deleteActivityParticipant(
        activityId: activityId.value,
        userId: userId,
      );
      
      if (response.isSuccess) {
        debugPrint('✅ 参与者删除成功');
        
        // 从本地列表移除
        participants.removeWhere((p) => p.userId == userId);
        isEmpty.value = participants.isEmpty;
        
        debugPrint('   剩余参与者: ${participants.length}');
      } else {
        debugPrint('❌ 参与者删除失败: ${response.message}');
      }
    } catch (e) {
      debugPrint('❌ 删除参与者异常: $e');
    }
  }
  
  /// 显示删除确认对话框
  Future<void> showRemoveDialog(int userId, String username) async {
    final confirmed = await Get.dialog<bool>(
      AlertDialog(
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(16),
        ),
        title: Row(
          children: [
            Container(
              padding: const EdgeInsets.all(8),
              decoration: BoxDecoration(
                gradient: const LinearGradient(
                  colors: [Color(0xFFFF6B6B), Color(0xFFD84545)],
                ),
                borderRadius: BorderRadius.circular(10),
              ),
              child: const Icon(
                Icons.warning_rounded,
                color: Colors.white,
                size: 20,
              ),
            ),
            const SizedBox(width: 12),
            const Text(
              '移除参与者',
              style: TextStyle(
                fontSize: 17,
                fontWeight: FontWeight.bold,
                color: Color(0xFF333333),
              ),
            ),
          ],
        ),
        content: Padding(
          padding: const EdgeInsets.only(top: 8),
          child: Text(
            '确定要从活动中移除「$username」吗？',
            style: const TextStyle(
              fontSize: 15,
              color: Color(0xFF666666),
              height: 1.5,
            ),
          ),
        ),
        actions: [
          // 取消按钮
          TextButton(
            onPressed: () => Get.back(result: false),
            style: TextButton.styleFrom(
              padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 12),
            ),
            child: const Text(
              '取消',
              style: TextStyle(
                fontSize: 15,
                color: Color(0xFF999999),
              ),
            ),
          ),
          // 确认按钮（渐变）
          Container(
            decoration: BoxDecoration(
              gradient: const LinearGradient(
                colors: [Color(0xFFFF6B6B), Color(0xFFD84545)],
              ),
              borderRadius: BorderRadius.circular(8),
            ),
            child: TextButton(
              onPressed: () => Get.back(result: true),
              style: TextButton.styleFrom(
                padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 12),
                foregroundColor: Colors.white,
              ),
              child: const Text(
                '确定移除',
                style: TextStyle(
                  fontSize: 15,
                  fontWeight: FontWeight.w600,
                ),
              ),
            ),
          ),
        ],
      ),
    );
    
    if (confirmed == true) {
      await removeParticipant(userId, username);
    }
  }
}

